#!/usr/bin/env python
################################################################################
#            __  __            _   ____        _ _ ____        _              #
#           |  \/  | ___  __ _| |_| __ )  __ _| | | __ )  ___ | |_           #
#           | |\/| |/ _ \/ _` | __|  _ \ / _` | | |  _ \ / _ \| __|         #
#           | |  | |  __/ (_| | |_| |_) | (_| | | | |_) | (_) | |_          #
#           |_|  |_|\___|\__,_|\__|____/ \__,_|_|_|____/ \___/ \__|          #
#                                                                             #
#                                     by                                       #
# _______ .______       _______  _______   ______   ______   _______   _______  #
#|   ____||   _  \     |   ____||   ____| /      | /  __  \ |       \ |   ____|  #
#|  |__   |  |_)  |    |  |__   |  |__   |  ,----'|  |  |  ||  .--.  ||  |__      #
#|   __|  |      /     |   __|  |   __|  |  |     |  |  |  ||  |  |  ||   __|      #
#|  |     |  |\  \----.|  |____ |  |____ |  `----.|  `--'  ||  '--'  ||  |____      #
#|__|     | _| `._____||_______||_______| \______| \______/ |_______/ |_______|    #
#                                                                                 #
#                                Message Core                                    #
#                             Circuits FrameWork                                #
#
# Coders
#
#	Justin Giorgi (rebel_kid)
#
# Debuggers
#
#	Justin Giorgi (rebel_kid)
#	Lachlan Gilmour (chilli0)
#	David Liedle (spiderbyte)
#	(Polarina)
#	(prologic)
#
################################################################################
#                                                                              #
#                               GPL Licensed                                   #
#                                                                              #
################################################################################

# Imports
from circuits.core import listener, Event, Component

# Sets plugin variables
__id__ = "messagehandler"
__core__ = True

# Creates event classes
class PubMsg(Event): pass
class Command(Event): pass
class Message(Event): pass
class PrivCmd(Event): pass

class Message(Component):

	def __init__(self, *args, **kwargs):
		# Important: Call the super constructors to initialize the Component.
		super(Network, self).__init__(*args, **kwargs)
		self.channel = kwargs["channel"]
		
	@listener("relay-message")
	def onMESSAGE(self, cursor, identified, source, target, message):
		# Splits public and private messages
		if "#" in target:
			self.push(PubMsg(cursor, identified, source, target, message), "relay-pubmsg", self.channel)
		else:
			self.push(PrivMsg(cursor, identified, source, target, message), "relay-privmsg", self.channel)
	
	@listener("relay-pubmsg")
	def onPUBMSG(self, cursor, identified, source, target, message):
		# Gets message variables
		destination = target
		ident = source.split("!")[1].split("@")[0]
		host = source.split("@")[1]
		source = source.split("!")[0]
		channel = target
		command = message.split(" ")
		
		# Checks for a command and issues a command event
		if message.startswith(callsign):
			# Strips callsign
			command[0] = "".join(map(str, command[0])[1:])
			
			# Gets mysql data
			data = self.getdata(ident, host, source, destination, command, channel)
			chanid = data[0]
			callsign = data[1]
			delay = data[2]
			features = delay[3]
			nickid = delay[4]
			access = delay[5]
			botadmin = delay[6]
			feature = delay[7]
			
			# Pushes event
			self.push(Command(cursor = cursor, destination = destination,  ident = ident, host = host, source = source, channel = channel, command = command, chanid = chanid, callsign = callsign, delay = delay, features = features, nickid = nickid, access = access, botadmin = botadmin,  private = False), "command-%s" % (feature), self.channel)
		
		# Issues a message event
		self.push(Message(cursor = cursor, identified = identified, destination = destination, ident = ident, host = host, source = source, channel = channel, command = command, private = False), "polished-message", self.channel)
	
	@listener("relay-privmsg")
	def onPRIVMSG(self, cursor, identified, source, target, message):
		# Gets message variables
		ident = source.split("!")[1].split("@")[0]
		host = source.split("@")[1]
		source = source.split("!")[0]
		destination = source
		command = message.split(" ")
		
		# Checks if message is an out-of-channel command
		if message.startswith("#"):
			channel = command[0]
			command = command[1:]
			
			# Gets mysql data
			data = self.getdata(ident, host, source, destination, command, channel)
			chanid = data[0]
			callsign = data[1]
			delay = data[2]
			features = delay[3]
			nickid = delay[4]
			access = delay[5]
			botadmin = delay[6]
			feature = delay[7]
			
			# Pushes event
			self.push(Command(cursor = cursor, destination = destination,  ident = ident, host = host, source = source, channel = channel, command = command, chanid = chanid, callsign = callsign, delay = delay, features = features, nickid = nickid, access = access, botadmin = botadmin,  private = True), "command-%s" % (feature), self.channel)
		
		# Issues private command event
		else:
			self.push(PrivCmd(cursor = cursor, identified = identified, destination = destination, ident = ident, host = host, source = source, channel = channel, command = command, private = True), "privcmd-%s" % (command[0].lower()), self.channel)
		
		# Issues a message event
		self.push(Message(cursor = cursor, identified = identified, destination = destination, ident = ident, host = host, source = source, channel = channel, command = command, private = True), "polished-message", self.channel)
		
			
	def getdata(ident, host, source, destination, command, channel):
		# Gets chanid, callsign and delay
		cursor.execute("SELECT id, callsign, delay FROM channels WHERE channame = %s AND active = 1", (channel))
		data = cursor.fetchone()
		if data is None:
			cursor.execute("SELECT id, callsign, delay FROM channels WHERE id = 0")
			data = cursor.fetchone()
			chanid = data[0]
			callsign = data[1]
			delay = data[2]
		else:
			chanid = data[0]
			callsign = data[1]
			delay = data[2]
		
		# Gets feature set
		cursor.execute("SELECT * FROM features WHERE chanid = %s", (chanid))
		data = cursor.fetchone()
		features = data[2:]
	
		# Gets nickid if identified
		if (ident, host) in identified:
			nickid = identified[(ident, host)]
		else:
			nickid = 0
		
		# Gets permissions
		cursor.execute("SELECT * FROM access WHERE nickid = %s AND active = 1", (nickid))
		data = cursor.fetchone()
		access = data[2:]
	
		# Gets botadmin
		cursor.execute("SELECT botadmin FROM users WHERE nickid = %s AND active = 1", (nickid))
		data = cursor.fetchone()
		botadmin = data[0]
		
		# Gets alias and command
		cursor.execute("SELECT command FROM users WHERE alias = %s", (command[0].lower()))
		data = cursor.fetchone()
		if data is None:
			feature = "factoid"
		else:
			feature = data[0]
		
		# Returns mysql data
		return (chanid, callsign, delay, features, nickid, access, botadmin, feature)
		
def startup(channel, cursor):
	plugin = Message(channel = channel, cursor = cursor)
	return (__id__, plugin)

def kill():
	return __id__
